#coding:utf-8
import base64
import face_recognition
import pickle
import psycopg2
from flask import request, render_template, flash
from faces import db
from faces.models import UserForm, UserInfo, UserKaoqin

from . import kaoqin

# 进行人脸的比对

@kaoqin.route("/kaoqin", methods=["GET", "POST"])
def kaoqin():
    forms = UserForm()
    if request.method == "POST":
        # 1. 得到前端页面传来的照片
        imgdata = request.form.get("myimg")
        img_base64_data = base64.b64decode(imgdata)
        with open("b.jpg", "wb") as f:
            f.write(img_base64_data)
        # 读取图片的过程其实就是把base64转为ndarray
        imgfile = face_recognition.load_image_file("b.jpg")
        # 2.对图片进行加工，编码为ndarray脸部数据
        # print(imgfile)
        try:
            # 这里尝试查询所有
            user_list_all = db.session.query(UserInfo).all()

            face_code = face_recognition.face_encodings(imgfile)[0]

            if face_code != []:

                for i, user in enumerate(user_list_all):
                # for user in user_list_all:
                    face_ndarray = pickle.loads(user.userphoto)

                    result = face_recognition.compare_faces(
                        face_ndarray, [face_code], 0.4)
                    # print(result[0])
                    # 如果匹配正确,允许登陆
                    if result[0]==True:
                        # print(user.username)

                        user01 = UserKaoqin.query.filter_by(user_name=user.username).first()
                        if user01:
                            print(user.username)
                            return "已存在"
                        else:
                            try:
                                new_kq = UserKaoqin(user_id=user.userid,user_name=user.username)
                                # 与user表中的id进行比较，相等的话，把kq表数据展示到表格
                                db.session.add(new_kq)
                                db.session.commit()
                                print("匹配正确")
                                return "成功"
                            except Exception as e:
                                db.session.rollback()
                                return "考勤失败"
        except Exception as e:
            return "未找到面部"

    kq = UserKaoqin.query.all()

    return render_template("kaoqin.html",kq=kq,form=forms)
